import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import torch
from torch.nn import functional as F

from .modules.context_module import *
from torch.nn import Module, Sequential, Conv2d, MaxPool2d, Parameter, Linear, Sigmoid, Softmax


__all__ = ['vgg19']
model_urls = {
    'vgg19': 'https://download.pytorch.org/models/vgg19-dcbb9e9d.pth',
}


class RegLayer(nn.Module):
    # dense decoder, it can be replaced by other decoder previous, such as DSS, amulet, and so on.
    # used after MSF
    def __init__(self, channel):
        super(RegLayer, self).__init__()
        
        self.reg_layer = nn.Sequential(
            nn.Conv2d(channel * 3, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(256, 128, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(128, 1, 1)
        )

        self.upsample = lambda img, size: F.interpolate(img, size=size, mode='bilinear', align_corners=True)
        
    def forward(self, f3, f2, f1):
        f3 = self.upsample(f3, f1.shape[-2:])
        f2 = self.upsample(f2, f1.shape[-2:])
        f3X2 = torch.mul(f3,f2)
        f3X1 = torch.mul(f3X2,f1)
        f3 = torch.cat([f3, f3X2 ,f3X1], dim=1)

        for i in range(len(self.reg_layer)):
            if i == len(self.reg_layer) - 1:
                out = self.reg_layer[i](f3)
            else:
                f3 = self.reg_layer[i](f3)
            
        return f3, out


class VGG(nn.Module):
    def __init__(self, features):
        super(VGG, self).__init__()
        self.features = features

        channels = 128
        self.context2 = RFB_GAP(256, channels, 2)
        self.context3 = RFB_GAP(512, channels, 4)
        self.context4 = RFB_GAP(512, channels, 4)

        self.decoder = RegLayer(channels)

    def forward(self, x):
        xs = []
        for i in range(len(self.features)):
            x = self.features[i](x)
            if i in [4, 9, 18, 26, 35]:
                xs.append(x)
        x0, x1, x2, x3, x4 = xs
        
        x2 = self.context2(x2)
        x3 = self.context3(x3)
        x4 = self.context4(x4)
       
        f5, a5 = self.decoder(x4, x3, x2)

        return torch.abs(a5)
        """
        x = self.features(x)
        x = F.upsample_bilinear(x, scale_factor=2)
        x = self.reg_layer(x)
        return torch.abs(x)
        """


def make_layers(cfg, batch_norm=False):
    layers = []
    in_channels = 3
    for v in cfg:
        if v == 'M':
            layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
        else:
            conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)
            if batch_norm:
                layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]
            else:
                layers += [conv2d, nn.ReLU(inplace=True)]
            in_channels = v
    return nn.Sequential(*layers)

cfg = {
    'E': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512]
}

def vgg19():
    """VGG 19-layer model (configuration "E")
        model pre-trained on ImageNet
    """
    model = VGG(make_layers(cfg['E']))
    model.load_state_dict(model_zoo.load_url(model_urls['vgg19']), strict=False)
    return model

